/*
 * Copyright (c) 2023-11-7
 * 说明:
 */

package ajaxSign

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"feng-che.com/server/driver-quiz/internal/sysLogger"
	"fmt"
	"os"
)

var PrivateKeyForCommunicate *rsa.PrivateKey

func GenCommuKey() {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err.Error())
	}
	err = privateKey.Validate()
	if err != nil {
		fmt.Println("key erros," + err.Error())
	}
	privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
	publicKeyBytes := x509.MarshalPKCS1PublicKey(&privateKey.PublicKey)
	block := pem.Block{
		Type:  "privateKey",
		Bytes: privateKeyBytes,
	}
	filePrivate, err := os.Create("./tmp/privateKey.pem")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	filePublic, err := os.Create("./tmp/publicKey.pem")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	err = pem.Encode(filePrivate, &block)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	filePrivate.Close()
	block = pem.Block{
		Type:  "publicKey",
		Bytes: publicKeyBytes,
	}
	err = pem.Encode(filePublic, &block)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}

// ReadCommuPrivateKey 由本地读取通讯的私钥
func ReadCommuPrivateKey() {
	readFile, err := os.ReadFile("./tmp/privateKey.pem")
	if err != nil {
		sysLogger.SysLog.WithField("err", err.Error()).Error("读取通讯密钥错误")
		return
	}
	block, _ := pem.Decode(readFile)
	if block.Type != "privateKey" {
		sysLogger.SysLog.WithField("type", block.Type).Warn("读取密钥类型不对")
		return
	}
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		sysLogger.SysLog.WithField("err", err.Error()).Warn("密钥分析不对")
		return
	}
	if privateKey.Validate() != nil {
		sysLogger.SysLog.WithField("not validate", privateKey.Validate().Error()).Warn("密钥无效")
	}
	PrivateKeyForCommunicate = privateKey
}
